package cn.itcast.com.network.udp.v1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class Sender {
    public static void main(String[] args) throws IOException {

        //获取键盘的输入
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        //创建套接字对象
        DatagramSocket datagramSocket = new DatagramSocket(8080);
        //创建一个字符串接受键盘的输入
        String data;
        while ((data = bufferedReader.readLine()) != null){
            sendData(datagramSocket, data);
            //如果发送的是886,则中断
            if (data.equals("886")){
                break;
            }

        }
        datagramSocket.close();
    }

    private static void sendData(DatagramSocket datagramSocket, String data) throws IOException {
        //将获得的数据转换成字节数组，方便待会的传参
        byte[] dataBytes = data.getBytes();
        //获得本机的ip地址
        InetAddress localHost = InetAddress.getLocalHost();
        //将参数都写入Packet中
        DatagramPacket datagramPacket = new DatagramPacket(dataBytes, 0, dataBytes.length, localHost, 8282);

        datagramSocket.send(datagramPacket);
    }
}
